<template>
    <el-cascader
        v-model="value"
        :options="options"
        :props="props"
        @change="handleChange"
        :show-all-levels="false"
    />
</template>

<script setup>
import {deptTreeSelectPost} from '@/api/system/user.js';
import useUserStore from '@/store/modules/user.js';

const emit = defineEmits(['modelValue', 'update:modelValue']);
const value = ref([]);

const useUser = useUserStore();
const {deptId} = useUser.info;
console.log(deptId)
// 配置选项
const props = {
    expandTrigger: 'hover',
    checkStrictly: true,
    value: 'id'
}

// 数据源
const options = ref([]);
const handleChange = (value) => {
    emit('update:modelValue', value ? Object.values(value).pop() : '');
}

// 获取数据源
const getData = async () => {
    // const sss = await listDept()
    const res = await deptTreeSelectPost({
        isUnit: true,
        deptId: deptId,
    });
    options.value = res.data
    // options.value = buildTree(res.data)
}

// 构建树形结构
const buildTree = (data) => {
    const map = {};
    data.map(item => {
        map[item.deptId] = {
            value: item.deptId,
            label: item.deptName
        };
    });

    const result = [];
    data.map(item => {
        const current = map[item.deptId];
        if (item.parentId === 0) {
            result.push(current);
        } else if (map[item.parentId]) {
            if (!map[item.parentId].children) {
                map[item.parentId].children = [];
            }
            map[item.parentId].children.push(current);
        }
    });

    return result;
}

onMounted(() => {
    getData()
})
</script>

<style scoped lang="scss">

</style>